const { app, BrowserWindow, ipcMain } = require("electron/main");
const path = require("node:path");
const fs = require("node:fs");

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, "preload.js")
    }
  });

  ipcMain.on("set-title", handleSetTitle);
  ipcMain.handle("write-file", handleWriteFile);

  win.loadFile("index.html");
  win.webContents.openDevTools();

  // const contents = win.webContents;
  // console.log("contents--", contents);

  return win
};

const handleSetTitle = (event, title) => {
  // console.log("the event", event);
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win.setTitle(title);
};

async function handleWriteFile(event, content) {
  console.log("the content", content);
  await fs.promises.writeFile("test.txt", content);
  const stats = await fs.promises.stat("test.txt");
  // console.log(stats)
  return stats.size;
}

app.whenReady().then(() => {
  let counter = 1
  const win = createWindow();
  win.webContents.send('update-counter', counter)
  setInterval(() => {
    counter += 3;
    win.webContents.send('update-counter', counter)
  }, 3000)

  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
